/**   
 * @Title: WebAccessTools.java
 * @Package com.willter.weather.utils
 * @Description: TODO(Android网络访问工具类)
 * 		<p>
 * @author willter
 * @date 2012-9-14
 */
package com.willter.weather.utils;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.widget.Toast;

/**
 * @ClassName: WebAccessTools
 * @Description: Android网络访问工具类
 *               <p>
 * @author willter
 * @date 2012-9-14
 */
public class WebAccessTools {

	private Context context;

	public WebAccessTools(Context context) {
		this.context = context;
	}

	/**
	 * @Title: getWebContent
	 * @Description: 通过制定的URL获取响应内容（GET请求方式）
	 *               <p>
	 * @author willter
	 * @date 2012-9-14
	 *       <p>
	 * @param url 请求URL
	 * @return 响应内容
	 */
	public String getWebContent(String url) {
		// 创建一个HTTP请求对象
		HttpGet request = new HttpGet(url);
		// 设置HTTP请求参数
		HttpParams params = new BasicHttpParams();
		// 设置连接超时
		//HttpConnectionParams.setConnectionTimeout(params, 3000);
		// 设置响应超时
		//HttpConnectionParams.setSoTimeout(params, 5000);
		// 创建网络访问对象
		HttpClient httpClient = new DefaultHttpClient(params);

		try {
			// 执行请求
			HttpResponse response = httpClient.execute(request);
			// 判断请求是否成功
			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
				String content = EntityUtils.toString(response.getEntity());
				return content;
			} else {
				Toast.makeText(context, "网络访问失败，请检查是否正确联网！", Toast.LENGTH_LONG).show();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 释放连接
			httpClient.getConnectionManager().shutdown();
		}

		return null;
	}
}
